//
//  cliqsetAppDelegate.m
//  cliqset
//
//  Created by David Hinson on 2/6/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "cliqsetAppDelegate.h"
#import "LoginViewController.h"
#import "Contact.h"
#import "ContactsViewController.h"
#import "FavoritesViewController.h"
#import "HoverView.h"
#import "EditAddressViewController.h"
#import "EditEmailViewController.h"
#import "EditIMViewController.h"
#import "EditURLViewController.h"
#import "EditUserViewController.h"
#import "EditPhoneViewController.h"
#import "EmailTypeViewController.h"
#import "IMTypeViewController.h"
#import "URLTypeViewController.h"
#import "PhoneTypeViewController.h"
#import "AddressTypeViewController.h"
#import "Event.h"
#import "HomeViewController.h"
#import "MessageViewController.h"
#import "ProfileDetailViewController.h"
#import "ProfileViewController.h"
#import "Relationship.h"
#import "RelationshipViewController.h"
#import "MessageDetailViewController.h"
#import "FormRelationshipsViewController.h"
#import "RelationshipDetailViewController.h"
#import "RelationshipDrillViewController.h"
#import "ChooseRecipientViewController.h"
#import "MessageComposeViewController.h"
#import "MessageDrillComposeViewController.h"
#import "MessageProfileComposeViewController.h"
#import "QueryUsersViewController.h"
#import "Message.h"

@implementation cliqsetAppDelegate

@synthesize window;
@synthesize tabBarController;
@synthesize isAuthenticated;
@synthesize isAuthenticating;
@synthesize isSyncing;
@synthesize loginViewController;

@synthesize splashViewController;

@synthesize loginString;
@synthesize passwordString;
@synthesize authenticationString;
@synthesize userString;

@synthesize favorites;
@synthesize contacts;
@synthesize toEvents;
@synthesize fromEvents;
@synthesize profileEvents;
@synthesize relationships;
@synthesize relationshipEvents;
@synthesize notifications;
@synthesize database;
@synthesize cliqset;
@synthesize currentProfile;

@synthesize incomingMessagesCount;
@synthesize incomingRequestsCount;

@synthesize currentTitle;

@synthesize currentStatus;
@synthesize eventStatus;
@synthesize relationshipStatus;
@synthesize messages;
@synthesize sentMessages;
@synthesize askedForRelationships;
@synthesize pendingRelationships;
@synthesize queryResults;

@synthesize viewTimer, watchDogTimer, reloadListView, updateContactsFlag, updateFavoritesFlag, blockWatchdog;

@synthesize watchDogTimer2;
@synthesize watchDogTimer3;
@synthesize watchDogTimer4;

#pragma mark ---- App Start ----

// App has launched, now let's do our initial setup
- (void)applicationDidFinishLaunching:(UIApplication *)application {
	
	self.contacts              = [[NSMutableArray array] init];	
	self.favorites             = [[NSMutableArray array] init];	
	self.toEvents              = [[NSMutableArray array] init];	
	self.fromEvents            = [[NSMutableArray array] init];	
	self.profileEvents         = [[NSMutableArray array] init];	
	self.relationships         = [[NSMutableArray array] init];	
	self.relationshipEvents    = [[NSMutableArray array] init];	
	self.notifications         = [[NSMutableArray array] init];	
	self.messages              = [[NSMutableArray array] init];	
	self.sentMessages          = [[NSMutableArray array] init];	
	self.askedForRelationships = [[NSMutableArray array] init];		
	self.pendingRelationships  = [[NSMutableArray array] init];		
	self.queryResults          = [[NSMutableArray alloc] init];
		
	// Allocate Database object
	database	               = [[Database alloc] init];
	
	self.currentStatus         = [[Status alloc] init];
	self.eventStatus           = [[Status alloc] init];
	self.relationshipStatus    = [[Status alloc] init];	
	self.incomingMessagesCount = 0;
	self.incomingRequestsCount = 0;
	
	// Initially block watchdog
	self.blockWatchdog = YES;
	
	// Restore state
	[self restoreState];
	
	// Create database, if needed
	[database createEditableCopyOfDatabaseIfNeeded];
	
	// Create messages table, if needed
	[database createMessagesTable];
	
	// Add the tab bar controller's current view as a subview of the window
	[window addSubview:tabBarController.view];
	
	// Instantiate cliqset
	self.cliqset = [[Cliqset alloc] init];
	
	self.isAuthenticating = YES;
	
	[self flipSplashToFront];	
	
	// Timer (once a second) used to refresh contact details if a user name changes at some point.
	[self resetTimer];
	viewTimer = [[NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES] retain];
	[[NSRunLoop currentRunLoop] addTimer:viewTimer forMode:NSDefaultRunLoopMode];
	
	// Watch Dog Timer for Profile Events (3 minutes = 180 seconds).
	[self resetWatchDogTimer];
	watchDogTimer = [[NSTimer timerWithTimeInterval:180.0 target:self selector:@selector(watchDogFired:) userInfo:nil repeats:YES] retain];
	[[NSRunLoop currentRunLoop] addTimer:watchDogTimer forMode:NSDefaultRunLoopMode];

	// Watch Dog Timer 2 for Status Changes (1 minute = 60)
	[self resetWatchDogTimer2];
	watchDogTimer2 = [[NSTimer timerWithTimeInterval:60.0 target:self selector:@selector(watchDog2Fired:) userInfo:nil repeats:YES] retain];
	[[NSRunLoop currentRunLoop] addTimer:watchDogTimer2 forMode:NSDefaultRunLoopMode];
	
	// Watch Dog Timer 3 for Relationship Requests (1 minute = 60)
	[self resetWatchDogTimer3];
	watchDogTimer3 = [[NSTimer timerWithTimeInterval:71.0 target:self selector:@selector(watchDog3Fired:) userInfo:nil repeats:YES] retain];
	[[NSRunLoop currentRunLoop] addTimer:watchDogTimer3 forMode:NSDefaultRunLoopMode];
	
	// Watch Dog Timer 4 for Messages (2 minutes = 120 seconds)
	[self resetWatchDogTimer4];
	watchDogTimer4 = [[NSTimer timerWithTimeInterval:120.0 target:self selector:@selector(watchDog4Fired:) userInfo:nil repeats:YES] retain];
	[[NSRunLoop currentRunLoop] addTimer:watchDogTimer4 forMode:NSDefaultRunLoopMode];
	
	// Authenticate user
	[self.cliqset authenticate];
}

// General messages
-(void)addTextToLog:(NSString *)text withCaption:(NSString *)caption {
    UIAlertView* myAlert = [[UIAlertView alloc] initWithTitle:caption message:text delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [myAlert show];
    [myAlert release];    
}

// Reload messages
-(IBAction)reloadMessages {
	[self.cliqset getMessages];
}

// show Contacts Hover View
-(void)showContactsHoverView:(BOOL)show {

	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactDetailViewController class]]) {
					[self slideContactOut];
					}
			}
			break;
		}
	}
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactsViewController class]]) {
					ContactsViewController* dref = (ContactsViewController*)f1;
					if (show) {
						dref.navigationItem.leftBarButtonItem.enabled  = NO;
						dref.navigationItem.rightBarButtonItem.enabled = NO;
						} 
					else {
						dref.navigationItem.leftBarButtonItem.enabled  = YES;
						dref.navigationItem.rightBarButtonItem.enabled = YES;
						}
					[dref showHoverView:show];
				}
			}
			break;
		}
	}

	[pool release];
}

// Reset segment control
-(void)resetSegment {
	
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactDetailViewController class]]) {
					[self slideContactOut];
				}
			}
			break;
		}
	}
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactsViewController class]]) {
					ContactsViewController* dref = (ContactsViewController*)f1;
					[dref resetSegment];
				}
			}
			break;
		}
	}
}

// show Favorites Hover View
-(void)showFavoritesHoverView {
	
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Favorites"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[FavoritesViewController class]]) {
					[self slideFavoriteOut];
				}
			}
			break;
		}
	}
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Favorites"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[FavoritesViewController class]]) {
					FavoritesViewController* dref = (FavoritesViewController*)f1;
					[dref showHoverView:YES];
				}
			}
			break;
		}
	}
}

// show Relationships Hover View
-(void)showRelationshipsHoverView:(BOOL)state {
	
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[RelationshipDetailViewController class]]) {
					[self slideRelationshipOut];
				}
			}
			break;
		}
	}
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[RelationshipViewController class]]) {
					RelationshipViewController* dref = (RelationshipViewController*)f1;
					[dref showHoverView:state];
					if (state) {
						dref.navigationItem.leftBarButtonItem.enabled  = NO;
						dref.navigationItem.rightBarButtonItem.enabled = NO;
					} 
					else {
						dref.navigationItem.leftBarButtonItem.enabled  = YES;
						dref.navigationItem.rightBarButtonItem.enabled = YES;
					}
				}
			}
			break;
		}
	}
}

// show Relationships Detail Hover View
-(void)showRelationshipsDetailHoverView:(BOOL)state {
	
	UINavigationController* nc;
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[RelationshipDetailViewController class]]) {
					RelationshipDetailViewController* dref = (RelationshipDetailViewController*)f1;
					[dref showHoverView:state];
				}
				if ([f1 isKindOfClass:[RelationshipViewController class]]) {
					RelationshipViewController* dref = (RelationshipViewController*)f1;
					[dref showHoverView:state];
				}
			}
			break;
		}
	}
}

// show Relationships Drill Hover View
-(void)showRelationshipsDrillHoverView:(BOOL)state {
	
	UINavigationController* nc;
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[RelationshipDrillViewController class]]) {
					RelationshipDrillViewController* dref = (RelationshipDrillViewController*)f1;
					[dref showHoverView:state];
				}
				if ([f1 isKindOfClass:[QueryUsersViewController class]]) {
					QueryUsersViewController* dref = (QueryUsersViewController*)f1;
					[dref showHoverView:state];
				}
				if ([f1 isKindOfClass:[RelationshipViewController class]]) {
					RelationshipViewController* dref = (RelationshipViewController*)f1;
					[dref showHoverView:state];
				}
			}
			break;
		}
	}
}

// show Query Results Hover View
-(void)showQueryResultsHoverView:(BOOL)state {
	
	UINavigationController* nc;
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[QueryUsersViewController class]]) {
					QueryUsersViewController* dref = (QueryUsersViewController*)f1;
					[dref showHoverView:state];
				}
			}
			break;
		}
	}
}

// Display Events Badge
-(void)showEventsBadge:(NSString*)badge {	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	UINavigationController* nc;
		
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Events"]) {
			nc = (UINavigationController *)vc;
			nc.tabBarItem.badgeValue = badge;
			break;
			}
		}
	[pool release];
}

// Display Contacts Badge
-(void)showContactsBadge:(NSString*)badge {
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	UINavigationController* nc;
	
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			nc.tabBarItem.badgeValue = badge;
			break;
			}
		}
	[pool release];
}

// Display Messages Badge
-(void)showMessagesBadge:(NSString*)badge {
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	UINavigationController* nc;
	
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Messages"]) {
			nc = (UINavigationController *)vc;
			nc.tabBarItem.badgeValue = badge;
			break;
		}
	}
	[pool release];
}

// Display Relationships Badge
-(void)showRelationshipsBadge:(NSString*)badge {
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	UINavigationController* nc;
	
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			nc.tabBarItem.badgeValue = badge;
			break;
		}
	}
	[pool release];
}

// show Events Hover View
-(void)showEventsHoverView:(BOOL)show {
	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Events"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactDetailViewController class]]) {
					// TODO
					// Will need to slide events out, eventually
					//[self slideContactOut];
				}
			}
			break;
		}
	}
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Events"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[HomeViewController class]]) {
					HomeViewController* dref = (HomeViewController*)f1;
					[dref showHoverView:show];
					if (show) {
						dref.navigationItem.leftBarButtonItem.enabled = NO;
					} 
					else {
						dref.navigationItem.leftBarButtonItem.enabled = YES;
					}
				}
				if ([f1 isKindOfClass:[ProfileDetailViewController class]]) {
					{ProfileDetailViewController* dref = (ProfileDetailViewController*)f1;
					[dref showHoverView:show];
						if (show) {
							dref.navigationItem.leftBarButtonItem.enabled = NO;
						} 
						else {
							dref.navigationItem.leftBarButtonItem.enabled = YES;
						}
					}
				}
			}
			break;
		}
	}
	[pool release];
}

-(void)setHomeProfileName:(NSString*)name {

	UINavigationController* nc;
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ProfileViewController class]]) {
					{ProfileViewController* dref = (ProfileViewController*)f1;
					[dref setHeaderName:name];
					}
				}
			}
			break;
		}
	}
}

-(void)setEventProfileName:(NSString*)name {
	
	UINavigationController* nc;
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Events"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ProfileDetailViewController class]]) {
					{
					ProfileDetailViewController* dref = (ProfileDetailViewController*)f1;
					[dref setHeaderName:name];
					}
				}
			}
			break;
		}
	}
}

-(void)setRelationshipProfileName:(NSString*)name {
	
	UINavigationController* nc;
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[RelationshipDetailViewController class]]) {
					{
						RelationshipDetailViewController* dref = (RelationshipDetailViewController*)f1;
						[dref setHeaderName:name];
					}
				}
			}
			break;
		}
	}
}

-(void)setHomeProfileStatus:(NSString*)status timestamp:(NSString*)timestamp {
	
	UINavigationController* nc;
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ProfileViewController class]]) {
					{ProfileViewController* dref = (ProfileViewController*)f1;
						[dref setHeaderStatus:status timestamp:timestamp];
					}
				}
			}
			break;
		}
	}
}

-(void)setEventProfileStatus:(NSString*)status timestamp:(NSString*)timestamp {
	
	UINavigationController* nc;
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Events"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ProfileDetailViewController class]]) {
					{
					ProfileDetailViewController* dref = (ProfileDetailViewController*)f1;
					[dref setHeaderStatus:status timestamp:timestamp];
					}
				}
			}
			break;
		}
	}
}

-(void)setRelationshipProfileStatus:(NSString*)status timestamp:(NSString*)timestamp {
	
	UINavigationController* nc;
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				NSLog(@"%@", f1);
				if ([f1 isKindOfClass:[RelationshipDetailViewController class]]) {
					{
						RelationshipDetailViewController* dref = (RelationshipDetailViewController*)f1;
						[dref setHeaderStatus:status timestamp:timestamp];
					}
				}
			}
			break;
		}
	}
}

// show Messages Hover View
-(void)showMessagesHoverView:(BOOL)show {
	
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Messages"]) {
			nc = (UINavigationController *)vc;
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[MessageViewController class]]) {
					{MessageViewController* dref = (MessageViewController*)f1;
						[dref showHoverView:show];
						if (show) {
							dref.navigationItem.leftBarButtonItem.enabled  = NO;
							dref.navigationItem.rightBarButtonItem.enabled = NO;
						} 
						else {
							dref.navigationItem.leftBarButtonItem.enabled  = YES;
							dref.navigationItem.rightBarButtonItem.enabled = YES;
						}
					}
				}
			}
			break;
		}
	}
}

// show Profile Hover View
-(void)showProfileHoverView:(BOOL)show {
	
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactDetailViewController class]]) {
					// TODO
					// Will need to slide profile out, eventually
					//[self slideContactOut];
				}
			}
			break;
		}
	}
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ProfileViewController class]]) {
					{ProfileViewController* dref = (ProfileViewController*)f1;
						[dref showHoverView:show];
						if (show) {
							//dref.navigationItem.leftBarButtonItem.enabled  = NO;
							//dref.navigationItem.rightBarButtonItem.enabled = NO;
							} 
						else {
							dref.navigationItem.leftBarButtonItem.enabled  = YES;
							dref.navigationItem.rightBarButtonItem.enabled = YES;
							}
						}
					}
				if ([f1 isKindOfClass:[ProfileDetailViewController class]]) {
					{ProfileDetailViewController* dref = (ProfileDetailViewController*)f1;
					[dref showHoverView:show];
					if (show) {
						dref.navigationItem.leftBarButtonItem.enabled  = NO;
						dref.navigationItem.rightBarButtonItem.enabled = NO;
						} 
					else {
						dref.navigationItem.leftBarButtonItem.enabled  = YES;
						dref.navigationItem.rightBarButtonItem.enabled = YES;
						}
					}
				}
			}
			break;
		}
	}
}

// Reload Background Relationships table
-(void)reloadBGRelationshipsTable {
	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	
	UINavigationController* nc;
	
	// Then, reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[RelationshipViewController class]]) {
					RelationshipViewController* dref = (RelationshipViewController*)f1;
					[dref reloadData];
				}
			}
			break;
		}
	}
	
	[pool release];
}

// Reload Relationships table
-(void)reloadRelationshipsTable {
	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	
	UINavigationController* nc;
	
	// Then, reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[RelationshipViewController class]]) {
					RelationshipViewController* dref = (RelationshipViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
					[dref showHoverView:NO];
				}
			}
			break;
		}
	}
	
	[pool release];
}

// Reload Relationships Detail table
-(void)reloadRelationshipsDetailTable {
	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	
	UINavigationController* nc;
	
	// Then, reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[RelationshipViewController class]]) {
					RelationshipDetailViewController* dref = (RelationshipDetailViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
				}
			}
			break;
		}
	}
	
	[pool release];
}

// Reload contacts table
-(void)reloadContactsTable {

	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	
	UINavigationController* nc;
	
	// First, slide out if we need to
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactDetailViewController class]]) {
					[self slideContactOut];
					}
				}
			break;
		}
	}
	
	// Then, reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactsViewController class]]) {
					ContactsViewController* dref = (ContactsViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
				}
			}
			break;
		}
	}

	[pool release];
}

// Reload events table
-(void)reloadEventsTable {
	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	UINavigationController* nc;
	
	// Reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Events"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[HomeViewController class]]) {
					//if ([f1 isKindOfClass:[HomeViewController class]] && (self.cliqset.mode == 14)) {
					HomeViewController* dref = (HomeViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
					[dref showHoverView:NO];
				}
				if ([f1 isKindOfClass:[ProfileDetailViewController class]]) {
					//if ([f1 isKindOfClass:[ProfileDetailViewController class]] && (self.cliqset.mode == 15)) {
					ProfileDetailViewController* dref = (ProfileDetailViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
					[dref showHoverView:NO];
				}
			}
			break;
		}
	}
	[pool release];
}

// Reload query results table
-(void)reloadQueryResultsTable {
	
	UINavigationController* nc;
	
	// Reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[QueryUsersViewController class]]) {
					QueryUsersViewController* dref = (QueryUsersViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
					[dref showHoverView:NO];
				}
			}
			break;
		}
	}
}

// Reload messages table
-(void)reloadMessagesTable {
	
	UINavigationController* nc;
	
	// Reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Messages"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[MessageViewController class]]) {
					MessageViewController* dref = (MessageViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
					[dref showHoverView:NO];
				}
			}
			break;
		}
	}
}

// Reload background messages table
-(void)reloadBGMessagesTable {
	
	UINavigationController* nc;
	
	// Reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Messages"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[MessageViewController class]]) {
					MessageViewController* dref = (MessageViewController*)f1;
					[dref reloadData];
				}
			}
			break;
		}
	}
}

// Reload profile events table
-(void)reloadProfileTable {
	
	UINavigationController* nc;
	
	// Reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ProfileViewController class]]) {
					ProfileViewController* dref = (ProfileViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
					[dref showHoverView:NO];
				}
			}
			break;
		}
	}
}

// Reload profile events table in background
-(void)reloadProfileTableBG {
	
	UINavigationController* nc;
	
	// Reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ProfileViewController class]]) {
					ProfileViewController* dref = (ProfileViewController*)f1;
					[dref reloadData];
					}
				}
			break;
			}
		}
}

// Reload profile events table
-(void)reloadProfileTableSilent {
	
	UINavigationController* nc;
	
	// Reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ProfileViewController class]]) {
					//if ([f1 isKindOfClass:[ProfileViewController class]] && (self.cliqset.mode == 19)) {
					ProfileViewController* dref = (ProfileViewController*)f1;
					[dref reloadData];
				}
			}
			break;
		}
	}
}

// Reload favorites table
-(void)reloadFavoritesTable {
	
	UINavigationController* nc;
	
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Favorites"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[FavoritesViewController class]]) {
					FavoritesViewController* dref = (FavoritesViewController*)f1;
					[dref reloadData];
					}
				else {
					[self slideFavoriteOut];
				}
			}
			break;
		}
	}
}

#pragma mark Handle View Flipping Here

-(void)flipSplashToFront {
	
	self.tabBarController.view.hidden = YES;
	SplashViewController* splash = [[SplashViewController alloc] initWithNibName:@"Splash" bundle:nil];
	[self setSplashViewController:splash];
	
	[self.window addSubview:[splash view]];
	
	[splash release];
}

-(void)flipSplashToBack {
	
	self.tabBarController.view.hidden = NO;
	[splashViewController.view removeFromSuperview];
	[splashViewController release];
	splashViewController=nil;
}

-(void)flipLoginToFront {
	
	LoginViewController* aLogin = [[LoginViewController alloc] initWithNibName:@"LoginView" bundle:nil];
	[self setLoginViewController:aLogin];
	
	[self.window addSubview:[aLogin view]];
	[aLogin.f1 becomeFirstResponder];
	
	[aLogin release];
}

-(void)flipLoginToBack {
	
	[loginViewController.view removeFromSuperview];
	[loginViewController release];
	loginViewController=nil;
}

#pragma mark ---- Asked For Relationship ----

-(void)addAskedForRelationship:(Target *)request {
	[askedForRelationships addObject:request];
}

#pragma mark ---- Pending Relationship ----

-(void)addPendingRelationship:(Target *)request {
	[pendingRelationships addObject:request];
}

#pragma mark ---- Relationship ----

-(void)addRelationship:(Relationship *)relationship {
	[relationships addObject:relationship];
}

#pragma mark ---- Profile ----

-(void)addProfile:(Profile *)incomingProfile {
	self.currentProfile = [incomingProfile retain];
}

#pragma mark ---- Status ----

-(void)addStatus:(Status *)incomingStatus {
	
	if (incomingStatus.mode == 16) {
		self.currentStatus.status     = incomingStatus.status;
		self.currentStatus.timeStamp  = (NSMutableString*)[incomingStatus.timeStamp description];
		}
	if (incomingStatus.mode == 23) {
		self.eventStatus.status     = incomingStatus.status;
		self.eventStatus.timeStamp  = (NSMutableString*)[incomingStatus.timeStamp description];
	}
	if (incomingStatus.mode == 24) {
		self.relationshipStatus.status     = incomingStatus.status;
		self.relationshipStatus.timeStamp  = (NSMutableString*)[incomingStatus.timeStamp description];
	}
}

#pragma mark ---- Contacts ----

-(void)addContact:(Contact*)contact {
	[contacts addObject:(id)contact];
}

#pragma mark ---- Query Results ----

-(void)addQuery:(Profile*)profile {
	[queryResults addObject:(id)profile];
}

#pragma mark ---- Messages ----

-(void)addMessage:(Message*)message {
	
	// List messages
	if (message.mode == 25 || message.mode == 125) {
		[messages addObject:(id)message];
		}

	// List messages
	if (message.mode == 28) {
		[messages addObject:(id)message];
		//[sentMessages addObject:(id)message];
	}
	
	// Populate contents of individual message
	if (message.mode == 26) {
		for (int x=0; x<[messages count]; x++) {
			Message * curMess = (Message *)[messages objectAtIndex:x];
			if ([message.messageIdentifier isEqualToString:curMess.messageIdentifier]) {
				if (curMess.body) {[curMess.body release];}
				curMess.body = [message.body copy];
				}
			}
		}
}

#pragma mark ---- Events ----

-(void)addEvent:(Event*)event {
	
	// To Events
	if (event.mode == 14) {
		[toEvents addObject:(id)event];
	}
	
	// From Events
	if (event.mode == 15) {
		[fromEvents addObject:(id)event];
	}
	
	// Profiles
	if (event.mode == 19 || event.mode == 119) {
		[profileEvents addObject:(id)event];
	}

	// Relationships
	if (event.mode == 21 || event.mode == 35) {
		[relationshipEvents addObject:(id)event];
	}
}
	
#pragma mark ---- Favorite Detail ----

// Slide Favorite Detail Out of View
-(void)slideFavoriteOut {
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Favorites"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Favorite Detail Into View
-(void)slideFavoriteIn:(NSInteger)index {
	
	ContactDetailViewController* aCV = [[ContactDetailViewController alloc] initWithNibName:@"ContactDetailView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Favorites"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index      = index;
	aCV.isFavorite = YES;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

#pragma mark ---- Contact Detail----

// Slide Add Contact Detail Into View
-(void)slideAddContactIn:(NSInteger)index {
	
	ContactDetailViewController* aCV = [[ContactDetailViewController alloc] initWithNibName:@"AddContactDetailView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Contact Detail Out of View
-(void)slideContactOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			break;
			}
		}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Message Detail Out of View
-(void)slideMessageDetailOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Messages"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Contact Detail Into View
-(void)slideContactIn:(NSInteger)index {
	
	ContactDetailViewController* aCV = [[ContactDetailViewController alloc] initWithNibName:@"ContactDetailView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
		
	aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Message Detail Into View
-(void)slideMessageDetailIn:(NSInteger)index {
	
	MessageDetailViewController* aCV = [[MessageDetailViewController alloc] initWithNibName:@"MessageDetailView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Messages"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Profile Detail Into View
-(void)slideProfileIn:(NSInteger)index {
	
	ProfileDetailViewController* aCV = [[ProfileDetailViewController alloc] initWithNibName:@"ProfileDetailView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Events"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Relationship Detail Out of View
-(void)slideRelationshipOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Relationship Drill Out of View
-(void)slideRelationshipDrillOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Relationship Detail Into View
-(void)slideRelationshipIn:(NSInteger)index {
	
	RelationshipDetailViewController* aCV = [[RelationshipDetailViewController alloc] initWithNibName:@"RelationshipDetailView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV setHeaderStatus:self.relationshipStatus.status timestamp:self.relationshipStatus.timeStamp];
	[aCV release];
}

// Slide Relationship Drill Down Into View
-(void)slideRelationshipDrillIn:(NSInteger)index {
	
	RelationshipDrillViewController* aCV = [[RelationshipDrillViewController alloc] initWithNibName:@"RelationshipDrillView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV setHeaderStatus:self.relationshipStatus.status timestamp:self.relationshipStatus.timeStamp];
	[aCV release];
}

// Slide Recipients Into View
-(void)slideRecipientsIn {
	
	ChooseRecipientViewController* aCV = [[ChooseRecipientViewController alloc] initWithNibName:@"ChooseRecipientView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Messages"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	//aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Query Users Into View
-(void)slideQueryUsersIn {
	
	QueryUsersViewController* aCV = [[QueryUsersViewController alloc] initWithNibName:@"QueryUsersView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Compose Out of View
-(void)slideComposeOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Messages"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Compose Drill Out of View
-(void)slideComposeDrillOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Compose Profile Out of View
-(void)slideComposeProfileOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Events"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Compose Drill Into View
-(void)slideComposeDrillIn:(int)index type:(int)type {
	
	MessageDrillComposeViewController* aCV = [[MessageDrillComposeViewController alloc] initWithNibName:@"MessageDrillComposeView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index = index;
	aCV.type  = type;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Compose Profile Into View
-(void)slideComposeProfileIn:(int)index {
	
	MessageProfileComposeViewController* aCV = [[MessageProfileComposeViewController alloc] initWithNibName:@"MessageProfileComposeView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Events"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Compose Into View
-(void)slideComposeIn:(int)index {
	
	MessageComposeViewController* aCV = [[MessageComposeViewController alloc] initWithNibName:@"MessageComposeView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Messages"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Relationships Pending Relationships Into View
-(void)slideRelationshipsPendingRelationshipsIn {
	
	FormRelationshipsViewController* aCV = [[FormRelationshipsViewController alloc] initWithNibName:@"FormRelationshipsView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	// aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Pending Relationships Into View
-(void)slidePendingRelationshipsIn {
	
	FormRelationshipsViewController* aCV = [[FormRelationshipsViewController alloc] initWithNibName:@"FormRelationshipsView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	// aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Address Type Into View
-(void)slideAddressTypeIn:(EditAddressViewController*)parent {
	
	AddressTypeViewController* aCV = [[AddressTypeViewController alloc] initWithNibName:@"AddressTypeView" bundle:nil];
	
	UINavigationController* nc = nil;

	// NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent = parent;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Address Type Out of View
-(void)slideAddressTypeOut:(EditAddressViewController*)parent {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[parent.addresses reloadData];
	
	[nc popViewControllerAnimated:YES];
}

// Slide IM Type Into View
-(void)slideIMTypeIn:(EditIMViewController*)parent {
	
	IMTypeViewController* aCV = [[IMTypeViewController alloc] initWithNibName:@"IMTypeView" bundle:nil];
	
	UINavigationController* nc = nil;

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent = parent;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide URL Type Into View
-(void)slideURLTypeIn:(EditURLViewController*)parent {
	
	URLTypeViewController* aCV = [[URLTypeViewController alloc] initWithNibName:@"URLTypeView" bundle:nil];
	
	UINavigationController* nc = nil;

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent = parent;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Email Type Into View
-(void)slideEmailTypeIn:(EditEmailViewController*)parent {
	
	EmailTypeViewController* aCV = [[EmailTypeViewController alloc] initWithNibName:@"EmailTypeView" bundle:nil];
	
	UINavigationController* nc = nil;

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent = parent;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide URL Type Out of View
-(void)slideURLTypeOut:(EditURLViewController*)parent {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[parent.urls reloadData];
	
	[nc popViewControllerAnimated:YES];
}

// Slide Email Type Out of View
-(void)slideEmailTypeOut:(EditEmailViewController*)parent {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[parent.emailAddresses reloadData];
	
	[nc popViewControllerAnimated:YES];
}

// Slide IM Type Out of View
-(void)slideIMTypeOut:(EditIMViewController*)parent {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[parent.ims reloadData];
	
	[nc popViewControllerAnimated:YES];
}

// Slide Phone Type Into View
-(void)slidePhoneTypeIn:(EditPhoneViewController*)parent {
	
	PhoneTypeViewController* aCV = [[PhoneTypeViewController alloc] initWithNibName:@"PhoneTypeView" bundle:nil];
	
	UINavigationController* nc = nil;

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent = parent;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Phone Type Out of View
-(void)slidePhoneTypeOut:(EditPhoneViewController*)parent {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[parent.phoneEdit reloadData];
	
	[nc popViewControllerAnimated:YES];
}

// Slide Address Out of View
-(void)slideAddressOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Address Edit Into View
-(void)slideAddressIn:(ContactDetailViewController*)parent label:(NSString*)label street:(NSString*)street locality:(NSString*)locality region:(NSString*)region postalCode:(NSString*)postalCode country:(NSString *)country {
	
	EditAddressViewController* aCV = [[EditAddressViewController alloc] initWithNibName:@"EditAddressView" bundle:nil];
	
	UINavigationController* nc = nil;

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent           = parent;
	aCV.addressTypeField = (NSMutableString*)[label lowercaseString];
	aCV.streetField      = (NSMutableString*)street;
	aCV.localityField    = (NSMutableString*)locality;
	aCV.regionField      = (NSMutableString*)region;
	aCV.postalCodeField  = (NSMutableString*)postalCode;
	aCV.countryField     = (NSMutableString*)country;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide URL Edit Into View
-(void)slideURLIn:(ContactDetailViewController*)parent label:(NSString*)label content:(NSString*)content {
	
	EditURLViewController* aCV = [[EditURLViewController alloc] initWithNibName:@"EditURLView" bundle:nil];
	
	UINavigationController* nc = nil;

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent       = parent;
	aCV.urlTypeField = (NSMutableString*)[label lowercaseString];
	aCV.urlField     = (NSMutableString*)content;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide User Edit Into View
-(void)slideUserIn:(ContactDetailViewController*)parent givenName:(NSString*)givenName familyName:(NSString*)familyName position:(NSString*)position company:(NSString*)company {
	
	EditUserViewController* aCV = [[EditUserViewController alloc] initWithNibName:@"EditUser" bundle:nil];
	
	UINavigationController* nc = nil;
	
	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent          = parent;
	aCV.givenNameField  = givenName == nil ? @"" : (NSMutableString*)givenName;
	aCV.familyNameField = familyName == nil ? @"" : (NSMutableString*)familyName;
	aCV.positionField   = position == nil ? @"" : (NSMutableString*)position;
	aCV.companyField    = company == nil ? @"" : (NSMutableString*)company;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide User Out of View
-(void)slideUserOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	// Tell app we need to update our list views
	self.updateContactsFlag  = YES;
	self.updateFavoritesFlag = YES;
	self.reloadListView      = YES;
	
	[nc popViewControllerAnimated:YES];
}

// Slide URL Out of View
-(void)slideURLOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide IM Edit Into View
-(void)slideIMIn:(ContactDetailViewController*)parent label:(NSString*)label content:(NSString*)content {
	
	EditIMViewController* aCV = [[EditIMViewController alloc] initWithNibName:@"EditIMView" bundle:nil];
	
	UINavigationController* nc = nil;

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent      = parent;
	aCV.imTypeField = (NSMutableString*)[label lowercaseString];
	aCV.imField     = (NSMutableString*)content;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide IM Out of View
-(void)slideIMOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Email Edit Into View
-(void)slideEmailIn:(ContactDetailViewController*)parent label:(NSString*)label content:(NSString*)content {
	
	EditEmailViewController* aCV = [[EditEmailViewController alloc] initWithNibName:@"EditEmailView" bundle:nil];
	
	UINavigationController* nc = nil;

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent           = parent;
	aCV.emailTypeField   = (NSMutableString*)[label lowercaseString];
	aCV.emailAddressField = (NSMutableString*)content;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Email Out of View
-(void)slideEmailOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Phone Edit Into View
-(void)slidePhoneIn:(ContactDetailViewController*)parent label:(NSString*)label content:(NSString*)content {
	
	EditPhoneViewController* aCV = [[EditPhoneViewController alloc] initWithNibName:@"EditPhoneView" bundle:nil];
	
	UINavigationController* nc = nil;
	
	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent           = parent;
	aCV.phoneTypeField   = (NSMutableString*)[label lowercaseString];
	aCV.phoneNumberField = (NSMutableString*)content;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Phone Out of View
-(void)slidePhoneOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	NSString *target =  @"Contacts";

    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Answer confirmation that we really want to logout.
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	
	// Answer logout question
	if (buttonIndex == 0 && !self.isSyncing) {
		self.isAuthenticated  = NO;
		self.isAuthenticating = YES;
		[self.cliqset logout];
		}
	
	// Answer Sync question
	if (buttonIndex == 0 && self.isSyncing) {		
		// Show busy indicator
		[self showContactsHoverView:YES];		
		// Reset contacts
		[self.contacts removeAllObjects];
		// Remove all existing contact table data
		[self.database clearTables];
		// Get user contacts
		[self.cliqset getUserContacts:self.userString reload:YES];
		}

	self.isSyncing = NO;
}

// Logout
-(IBAction)logout:(id)id {
    UIAlertView* myAlert = [[UIAlertView alloc] initWithTitle:@"cliqset" message:@"Do You Wish to Logout?" delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:nil];
	
	[myAlert addButtonWithTitle:@"No"];
	
    [myAlert show];
    [myAlert release];    
}

// We are checking this timer for incoming messages.  
- (void)watchDog4Fired:(NSTimer *)timer
{	
	if (!self.isAuthenticated) {return;}
	if (self.blockWatchdog) {return;}
	
	NSLog(@"watchDog4Fired - messages");
		
	[self.cliqset getBGMessages];
}

// We are checking this timer for relationship requests.  
- (void)watchDog3Fired:(NSTimer *)timer
{	
	if (!self.isAuthenticated) {return;}
	if (self.blockWatchdog) {return;}
	NSLog(@"watchDog3Fired - relationship requests");
	[self.cliqset getRelationshipRequests];
}

// We are checking this timer for status changes.  
- (void)watchDog2Fired:(NSTimer *)timer
{	
	if (!self.isAuthenticated) {return;}	
	if (self.blockWatchdog) {return;}
	NSLog(@"watchDog2Fired - status changes");
	[self.cliqset getCurrentStatus];
}

// We are checking this timer so that we may see if events or contacts need reloading.  
- (void)watchDogFired:(NSTimer *)timer
{	
	if (!self.isAuthenticated) {return;}
	if (self.blockWatchdog) {return;}

	NSLog(@"watchDogFired - profile events");
	[self.cliqset loadProfileEventsBG:self.userString reload:YES];
}	

// We are checking this timer so that we may readjust our viewport.  
- (void)timerFired:(NSTimer *)timer
{
	// Do we need to reload the contacts / favorites list views?
	if (reloadListView) {
		UINavigationController* nc = nil;
		
		//NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
		NSString *target =  @"Contacts";
		
		for( UIViewController* vc in [self tabBarController].viewControllers ) {
			NSString* testString = (NSString*)vc.title;
			if ([testString isEqualToString:target]) {
				nc = (UINavigationController *)vc;
				int count = 0;
				for (UIViewController* f1 in nc.viewControllers) {
					if (count++ > 0) return;
					//NSLog(@"%@", f1.title); 
				}
				break;
			}
		}
		
		if (nc == nil) {return;}
		
		reloadListView = NO;
		
		NSLog(@"Fired %@", target);
		
		if ([target isEqualToString:@"Contacts"]) {
			if (self.updateContactsFlag) {
				self.updateContactsFlag = NO;
				[self reloadContactsTable];
			}
		} 
		else {
			if (updateFavoritesFlag) {
				self.updateFavoritesFlag=NO;
				[self reloadFavoritesTable];
			}
		}
		
		// If we have an update still pending, then check one more time
		if (updateContactsFlag || updateFavoritesFlag) {self.reloadListView=YES;}
	}
}

-(void)resetTimer {
	[viewTimer invalidate];
	[viewTimer release];
	viewTimer = nil;
}

-(void)resetReloadTimer {
	[reloadTimer invalidate];
	[reloadTimer release];
	reloadTimer = nil;
}

-(void)resetWatchDogTimer {
	[watchDogTimer invalidate];
	[watchDogTimer release];
	watchDogTimer = nil;
}

-(void)resetWatchDogTimer2 {
	[watchDogTimer2 invalidate];
	[watchDogTimer2 release];
	watchDogTimer2 = nil;
}

-(void)resetWatchDogTimer3 {
	[watchDogTimer3 invalidate];
	[watchDogTimer3 release];
	watchDogTimer3 = nil;
}

-(void)resetWatchDogTimer4 {
	[watchDogTimer4 invalidate];
	[watchDogTimer4 release];
	watchDogTimer4 = nil;
}

#pragma mark ----- UITabBarController delegates ----

// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)mtabBarController didSelectViewController:(UIViewController *)viewController {
	
	// [super tabBarController:mtabBarController didSelectViewController:viewController];
	
	self.currentTitle = (NSMutableString*)viewController.title;

	if ([viewController.title isEqualToString:@"Home"]) {
		[self reloadProfileTableBG];
		[self.cliqset getCurrentStatus];
		}
	
	if ([viewController.title isEqualToString:@"Events"]) {
		// Clear events badge after we tab to it
		[self showEventsBadge:nil];
		}
	
	if ([viewController.title isEqualToString:@"Contacts"]) {
		// Clear contact badge after we tab to it
		[self showContactsBadge:nil];
		}

	if ([viewController.title isEqualToString:@"Relationships"]) {
		[self reloadBGRelationshipsTable];
		}
	
	if ([viewController.title isEqualToString:@"Messages"]) {
		[self reloadBGMessagesTable];
		}
}

#pragma mark ----- Save / Restore State ----

// Restore State
-(void)restoreState {
	NSUserDefaults *defaults          = [NSUserDefaults standardUserDefaults];
	NSMutableString * currentTabTitle = (NSMutableString*)[defaults stringForKey:@"currentTabTitle"];

	int iIndex=0;
	NSArray *tabOrderToSave = self.tabBarController.viewControllers;
	for (UIViewController *aViewController in tabOrderToSave) {
		//NSLog(@"%@", aViewController.title);
		if ([currentTabTitle isEqualToString:aViewController.title]) {
			self.tabBarController.selectedIndex = iIndex;
			break;
			}
		iIndex++;
	}
	
}

// Reset unread messages
-(void)resetUnreadMessages {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];	
	
	// Clear any previous notification for messages
	for (int x=0; x<[myApp.notifications count]; x++) {
		UIView * view = (UIView*)[myApp.notifications objectAtIndex:x];
		if (view.tag == -1) {
			[myApp.notifications removeObjectAtIndex:x];
			break;
		};
	}
	
	int count = 0;
	for (int x=0; x<[myApp.messages count]; x++) {
		Message * message = (Message *)[myApp.messages objectAtIndex:x];
		if ([message.read isEqualToString:@"false"]) {count++;}
	}
	
	// If we have no unread messages, we are done.
	if (count == 0) {
		[myApp reloadProfileTableSilent];
		[self showMessagesBadge:nil];
		return;
		}
	else {
		NSString * countString = [NSString stringWithFormat:@"%d", count];
		[self showMessagesBadge:countString];
		}
	
	NSMutableString* countString = [NSString stringWithFormat:@"%d", count];
	
	UIView * notification     = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
	UIColor* textColor        = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];	
	
	UIFont* teeny_font        = [UIFont systemFontOfSize:14];
	UIFont* bold_teeny_font   = [UIFont boldSystemFontOfSize:14];
	
	UIImage *graphic          = [UIImage imageNamed:@"mail_information.png"];
	UIImageView *showImage    = [[UIImageView alloc] initWithFrame:CGRectMake(5.0, ((40-(24 * graphic.size.height / graphic.size.width))/2.0), 24, 24 * (graphic.size.height / graphic.size.width))];		
	showImage.image           = graphic;
	
	CGSize constraintSize;
	constraintSize.width      = 250.0f;
	constraintSize.height     = MAXFLOAT;	
	CGSize offsetX1           = [@"You have " sizeWithFont:teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeTailTruncation];
	CGSize offsetX2           = [countString sizeWithFont:bold_teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeTailTruncation];
	CGSize offsetX3           = [@" unread messages" sizeWithFont:teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeTailTruncation];
	
	UILabel * label1 = [[UILabel alloc] initWithFrame:CGRectMake(34, 10, 200, 20)];
	label1.text      = [NSString stringWithFormat:@"You have "];
	label1.font      = teeny_font;
	label1.textColor = textColor;
	label1.backgroundColor = [UIColor clearColor];
	
	UILabel * label2 = [[UILabel alloc] initWithFrame:CGRectMake(34 + offsetX1.width, 10, offsetX2.width, 20)];
	label2.text      = countString;
	label2.font      = bold_teeny_font;
	label2.textColor = textColor;
	label2.backgroundColor = [UIColor clearColor];
	
	UILabel * label3 = [[UILabel alloc] initWithFrame:CGRectMake(34 + offsetX1.width + offsetX2.width, 10, offsetX3.width, 20)];
	label3.text      = [NSString stringWithFormat:@" unread messages"];
	label3.font      = teeny_font;
	label3.textColor = textColor;
	label3.backgroundColor = [UIColor clearColor];
	
	[notification addSubview:label1];
	[notification addSubview:label2];
	[notification addSubview:label3];
	[notification addSubview:showImage];
	
	notification.tag = -1;
	
	[myApp.notifications addObject:notification];
	
	[showImage release];
	[label1 release];
	[label2 release];
	[label3 release];
	[notification release];
	
	// Refresh the profile table on the home page
	[myApp reloadProfileTableSilent];
}

// Reset pending relationships
-(void)resetPendingRelationships {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Clear any previous notification for messages
	for (int x=0; x<[myApp.notifications count]; x++) {
		UIView * view = (UIView*)[myApp.notifications objectAtIndex:x];
		if (view.tag == -2) {
			[myApp.notifications removeObjectAtIndex:x];
			break;
		};
	}
	
	NSString * pendingCountString = [NSString stringWithFormat:@"%d", [myApp.pendingRelationships count]];
	UIView * notification     = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
	UIColor* textColor        = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];	
	
	UIFont* teeny_font        = [UIFont systemFontOfSize:14];
	UIFont* bold_teeny_font   = [UIFont boldSystemFontOfSize:14];
	
	UIImage *graphic          = [UIImage imageNamed:@"user1_information.png"];
	UIImageView *showImage    = [[UIImageView alloc] initWithFrame:CGRectMake(5.0, ((40-(24 * graphic.size.height / graphic.size.width))/2.0), 24, 24 * (graphic.size.height / graphic.size.width))];		
	showImage.image           = graphic;
	
	CGSize constraintSize;
	constraintSize.width      = 250.0f;
	constraintSize.height     = MAXFLOAT;	
	CGSize offsetX1           = [@"You have " sizeWithFont:teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeTailTruncation];
	CGSize offsetX2           = [pendingCountString sizeWithFont:bold_teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeTailTruncation];
	CGSize offsetX3           = [@" pending relationship requests" sizeWithFont:teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeTailTruncation];
	
	UILabel * label1 = [[UILabel alloc] initWithFrame:CGRectMake(34, 10, 200, 20)];
	label1.text      = [NSString stringWithFormat:@"You have "];
	label1.font      = teeny_font;
	label1.textColor = textColor;
	label1.backgroundColor = [UIColor clearColor];
	
	UILabel * label2 = [[UILabel alloc] initWithFrame:CGRectMake(34 + offsetX1.width, 10, offsetX2.width, 20)];
	label2.text      = [NSString stringWithFormat:@"%d", [myApp.pendingRelationships count]];
	label2.font      = bold_teeny_font;
	label2.textColor = textColor;
	label2.backgroundColor = [UIColor clearColor];
	
	UILabel * label3 = [[UILabel alloc] initWithFrame:CGRectMake(34 + offsetX1.width + offsetX2.width, 10, offsetX3.width, 20)];
	label3.text      = [NSString stringWithFormat:@" pending relationship requests"];
	label3.font      = teeny_font;
	label3.textColor = textColor;
	label3.backgroundColor = [UIColor clearColor];
	
	[notification addSubview:label1];
	[notification addSubview:label2];
	[notification addSubview:label3];
	[notification addSubview:showImage];
	
	notification.tag = -2;
	
	[myApp.notifications addObject:notification];
	
	[showImage release];
	[label1 release];
	[label2 release];
	[label3 release];
	[notification release];
}

-(NSDate*)dateFromISO8601:(NSString*)str {
	static NSDateFormatter* sISO8601 = nil;
	
	if (str == nil) {
		NSDate * today = [[[NSDate alloc] init] autorelease];
		return today;
	}
	
	if (!sISO8601) {
		sISO8601 = [[NSDateFormatter alloc] init];
		[sISO8601 setTimeStyle:NSDateFormatterFullStyle];
		[sISO8601 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];   
	}
	if ([str hasSuffix:@"Z"]) {
		str = [[str substringToIndex:(str.length-1)] 
			   stringByAppendingString:@"GMT"];
	}
	return [sISO8601 dateFromString:str];
}

-(NSString*)describeEventTimeStamp:(NSDate *)stamp {
	
	NSDate * stopDate    = [[NSDate alloc] init];
	NSTimeInterval start = [stamp timeIntervalSinceReferenceDate];
	NSTimeInterval stop  = [stopDate timeIntervalSinceReferenceDate];
	NSTimeInterval diff  = (stop - start);
	[stopDate release];
	
	NSMutableString * retDate = [[[NSMutableString alloc] init] autorelease];
	
	retDate = @"> 1 year ago";
	
	if (diff < 31536000) {retDate = @"> 1 month ago";}	
	if (diff < 2592000)  {retDate = (NSMutableString*)[@"" stringByAppendingFormat:@"%.0f days ago", diff / (60 * 60 * 24)];}
	if( diff < 172800)   {retDate = @"1 day ago";}
	if (diff < 86400)    {retDate = (NSMutableString*)[@"" stringByAppendingFormat:@"%.0f hours ago", diff / (60 * 60)];}
	if (diff <  7200)    {retDate = @"1 hour ago";}	
	if (diff < 3600)     {retDate = (NSMutableString*)[@"" stringByAppendingFormat:@"%.0f minutes ago", diff / 60];}
	if (diff < 60)       {retDate = (NSMutableString*)[@"" stringByAppendingFormat:@"%.0f seconds ago", diff];}
	if (diff < 10)       {retDate = @"a few seconds ago";}
	if (diff == 1)       {retDate = @"just now.";}
	
	return retDate;
}

// Save state data when the app shuts down
-(void)applicationWillTerminate:(UIApplication *)application {
	NSUserDefaults *standardUserDefaults = (NSUserDefaults *)[NSUserDefaults standardUserDefaults];	
	[standardUserDefaults setObject:self.currentTitle forKey:@"currentTabTitle"];
}

// Free up our junk
- (void)dealloc {
	[queryResults release];
	[askedForRelationships release];
	[pendingRelationships release];
	[sentMessages release];
	[messages release];
	[currentTitle release];
	[currentProfile release];
	[currentStatus release];
	[eventStatus release];
	[relationshipStatus release];
	[viewTimer release];
	[watchDogTimer release];
	[watchDogTimer2 release];
	[watchDogTimer3 release];
	[watchDogTimer4 release];
	[splashViewController release];
	[cliqset release];
	[database release];
	[notifications release];
	[relationshipEvents release];
	[relationships release];
	[profileEvents release];
	[fromEvents release];
	[toEvents release];
	[favorites release];
	[contacts release];
	[userString release];
	[authenticationString release];
	[loginString release];
	[passwordString release];
	[loginViewController release];
    [tabBarController release];
    [window release];
    [super dealloc];
}

@end

